package com.qf.fmall2202.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;

@Component
@ServerEndpoint("/webSocket/{oid}")
public class WebSocketServer {

    public static HashMap<String, Session> orderIdSessionMap = new HashMap<>();

    /**
     * websocket中路径收参要使用 @PathParam
     * 注意：别跟 controller中的路径收参搞混了，
     * controller中用的是 @PathVariable
     * @param oid
     */
    @OnOpen
    public void onOpen(@PathParam("oid") String oid,Session session){
        orderIdSessionMap.put(oid,session);
    }

    @OnClose
    public void onClose(@PathParam("oid") String oid) throws IOException {
        final Session session = orderIdSessionMap.get(oid);

        session.close();

        orderIdSessionMap.remove(oid);
    }

    /**
     * 推送消息的静态方法
      * @param oid 订单编号
     * @param msg 要推送的消息
     */
    public static void sendMsg(String oid,String msg) throws IOException {

        final Session session = orderIdSessionMap.get(oid);

        session.getBasicRemote().sendText(msg);

    }

}
